var http = require('http');
var express = require('express');
var app = express();
var mysql = require('./mysql'); //引入自定义模块mysql

http.createServer(app).listen(8000);

//跨域请求
app.all("*", function (req, res, next) {
	// if (!req.get("Origin")) return next();
	// use "*" here to accept any origin
	res.set("Access-Control-Allow-Origin", "http://localhost:8080");
	res.set("Access-Control-Allow-Methods", "GET,POST");
	res.set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
	// res.set('Access-Control-Allow-Max-Age', 3600);
	res.set("Access-Control-Allow-Credentials", "true");
	if ("OPTIONS" === req.method) return res.sendStatus(200);
	next();
});

//导航数据
app.get('/index', function (req, res) {
	mysql.table('b_nav').limit(4).select().then(function (data) {
		var arr = {};
		arr['nav'] = data;
		mysql.table('b_nav').limit(4, 1).select().then(function (data) {
			arr['contact'] = data;
			//res.json()输出接口数据,affextedRows被影响的数据数量
			res.json({ success_code: 200, message: arr, affextedRows: arr.affextedRows });
		})
	})
})

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
//首页数据
app.post('/home', function (req, res) {
	mysql.table('b_home').select().then(function (data) {
		var arr = {};
		arr['home'] = data;
		//res.json()输出接口数据,affextedRows被影响的数据数量
		res.json({ success_code: 200, message: arr, affextedRows: arr.affextedRows });
	})
})

//work数据
app.get('/work', function (req, res) {
	var w_id = req.query.wid;
	mysql.table('b_work').alias('w').join({
		table: 'b_list',
		join: 'left',
		as: 'l',
		on: ['w_id', 'w_id'],
	}).where("l.w_id=" + w_id).select().then(function (data) {
		var arr = {};
		arr['list'] = data;
		mysql.table('b_work').select().then(function (data) {
			arr['work'] = data;
			mysql.table('b_list').limit(1).where("l_id=" + req.query.lid).select().then(function (data) {
				arr['essay'] = data;
				res.json({ success_code: 200, message: arr, affextedRows: arr.affextedRows });
			})
		})
	})
})

//message添加数据
app.get('/message',function(req,res){
	// console.log(req.query);
	//先接收数据
	var data={
		m_name:req.query.m_name,
		m_email:req.query.m_email,
		m_content:req.query.m_content,
		m_time:req.query.time,
	}
	mysql.table('b_message').add(data).then(function(data){

	})
})

//message查询数据
app.get('/messages', function (req, res) {
	mysql.table('b_message').select().then(function (data) {
		var arr = {};
		arr['message'] = data;
			//res.json()输出接口数据,affextedRows被影响的数据数量
			res.json({ success_code: 200, message: arr, affextedRows: arr.affextedRows });
	})
})

//blog查询数据
app.get('/blog', function (req, res) {
	mysql.table('b_blog').select().then(function (data) {
		var arr = {};
		arr['blog'] = data;
			//res.json()输出接口数据,affextedRows被影响的数据数量
			res.json({ success_code: 200, message: arr, affextedRows: arr.affextedRows });
	})
})



